<template>
  <div>
    <div class="d-flex mt-2 w-100">
      <custom-radio-tag1 class="mb-1 w-100" :list="list" :value="index" is-scroll @change="tagChange" />
    </div>
    <customSearch ref="customSearch" placeholder="请输入企业名称" title="报警列表" :total="total" @search="handleSearch" @superSearch="openSuperSearch" />
    <div>
      <div v-if="listData.length > 0" class="common_list">
        <div v-for="(item, ind) in listData" :key="ind" class="list_item" @click="goToDetails(item)">
          <div class="content_area">
            <div class="number_order">{{ ind + 1 }}</div>
            <div v-if="active === '视频报警'" class="right_content video_list_item" :style="{ backgroundImage: `url(${item.screenshots !== '/'?item.screenshots:videoImg})` }">
              <div class="content_title" style="max-width: 100%">
                <b>{{ item.eventType }}</b>
                <span>{{ item.reportStatus }}</span>
              </div>
              <ul>
                <li>
                  <i class="iconfont c-text-color1">&#xe725;</i>
                  <div class="value">{{ item.companyName }}</div>
                </li>
                <!--                <li>-->
                <!--                  <i class="iconfont c-text-color5">&#xe6bb;</i>-->
                <!--                  <div class="label">监控区域：</div>-->
                <!--                  <div class="value">{{ item.monitorRegion }}</div>-->
                <!--                </li>-->
                <!--                <li>-->
                <!--                  <i class="iconfont c-text-color4">&#xe634;</i>-->
                <!--                  <div class="label">设备编号：</div>-->
                <!--                  <div class="value">{{ item.sbbh }}</div>-->
                <!--                </li>-->
                <li>
                  <i class="iconfont c-text-color2">&#xe67a;</i>
                  <div class="label">设备名称：</div>
                  <div class="value">{{ item.cameraname }}</div>
                </li>
                <li>
                  <i class="iconfont c-text-color3">&#xe67a;</i>
                  <div class="label">报警时间：</div>
                  <div class="value">{{ item.alarmTime }}</div>
                </li>
                <li>
                  <i class="iconfont c-text-color4">&#xe685;</i>
                  <div class="label">报警级别：</div>
                  <div class="value">{{ item['alarmlevel'] }}</div>
                </li>
                <li>
                  <i class="iconfont c-text-color5">&#xe685;</i>
                  <div class="label">是否生成处置任务：</div>
                  <div class="value">{{ item['ishandletask'] }}</div>
                </li>
                <li>
                  <i class="iconfont c-text-color6">&#xe685;</i>
                  <div class="label">是否误报：</div>
                  <div class="value">{{ item['isfalsereport'] }}</div>
                </li>
              </ul>
            </div>
            <div v-else class="right_content">
              <div class="content_title" style="max-width: 100%">
                {{ item.companyName?item.companyName:'/' }}
                <span>{{ item.alarmStatus }}</span>
              </div>
              <ul>
                <li>
                  <i class="iconfont c-text-color1">&#xe611;</i>
                  <div class="label">报警类别：</div>
                  <div class="value">{{ item.eventType }}</div>
                </li>
                <li>
                  <i class="iconfont c-text-color2">&#xe634;</i>
                  <div class="label">报警级别：</div>
                  <div class="value">{{ item.alarmLevel }}</div>
                </li>
                <li>
                  <i class="iconfont c-text-color3">&#xe685;</i>
                  <div class="label">报警时间：</div>
                  <div class="value">{{ item.alarmTime || item.monitorTime }}</div>
                </li>
                <li>
                  <i class="iconfont c-text-color4">&#xe685;</i>
                  <div class="label">报警状态：</div>
                  <div class="value">{{ item['reportStatus'] }}</div>
                </li>
                <li>
                  <i class="iconfont c-text-color5">&#xe685;</i>
                  <div class="label">是否生成处置任务：</div>
                  <div class="value">{{ item['isHandleTask'] }}</div>
                </li>
                <li>
                  <i class="iconfont c-text-color6">&#xe685;</i>
                  <div class="label">是否误报：</div>
                  <div class="value">{{ item['isFalseReport'] }}</div>
                </li>
                <template v-if="active === '传感器报警'">
                  <li>
                    <i class="iconfont c-text-color7">&#xe685;</i>
                    <div class="label">报警值：</div>
                    <div class="value">{{ item['itemValue'] }}</div>
                  </li>
                  <li>
                    <i class="iconfont c-text-color1">&#xe685;</i>
                    <div class="label">允许值：</div>
                    <div class="value">{{ item['rangeValue'] }}</div>
                  </li>
                </template>
              </ul>
            </div>
          </div>
        </div>
      </div>
      <customLoadmore ref="customLoadmore" :page-num="form.pageNum" :pages="pages" @load="handlePages" />
    </div>
    <van-popup v-model="superSearch" position="right" :style="{ width: '90%', height: '100%' }" lock-scroll close-on-popstate closeable class="custom-van-pop">
      <div class="pop-vertical-flex">
        <div class="pop-content">
          <template v-if="active === '视频报警'">
            <custom-timer title="报警时间" type="datetime" :start.sync="form.starTime" :end.sync="form.endTime" />
            <customPopCheckbox :list="selectOptionAll['环保-报警状态']" :check-value.sync="form.alarmStatus" title="报警状态" />
            <customPopCheckbox :list="selectOptionAll['报警预警级别']" :check-value.sync="form.alarmLevel" title="报警级别" />
            <customPopCheckbox :list="selectOptionAll['是否']" :check-value.sync="form.falseAlarm" title="是否误报" />
            <customPopCheckbox :list="selectOptionAll['是否']" :check-value.sync="form.handleStatus" title="是否生成处置任务" />
            <customPopCheckbox :is-multiple="false" :radio-list="sourceAlarmList" :radio-value.sync="form.alarmSource" title="报警来源" />
          </template>
          <template v-else-if="active === '传感器报警'">
            <custom-timer title="报警时间" type="datetime" :start.sync="form.starTime" :end.sync="form.endTime" />
            <customPopCheckbox :is-multiple="false" :radio-list="[{value:-1,label:'全部',text:'全部'},...selectOptionAll['排污许可证管理-监测信息-监测类型']]" :radio-value.sync="form.outputType" title="排放类型" />
            <customPopCheckbox :list="selectOptionAll['环保-传感器报警类别']" :check-value.sync="form.eventType" title="报警类别" />
            <customPopCheckbox :list="selectOptionAll['环保-报警预警级别']" :check-value.sync="form.alarmLevel" title="报警级别" />
            <customPopCheckbox :list="selectOptionAll['环保-报警状态']" :check-value.sync="form.reportStatus" title="报警状态" />
            <!-- 监测指标 -->
            <customPopCheckbox :is-multiple="false" :radio-list="monitoringIndicatorsArr" :radio-value.sync="form.alarmItem" title="监测指标" />
          </template>
          <template v-else-if="active === '设备联动报警'">
            <custom-timer title="设备联动报警时间" type="datetime" :start.sync="form.starTime" :end.sync="form.endTime" />
            <!-- 生产设备和治理设备 -->
            <template v-for="item in equipmentRadio">
              <customPopCheckbox
                :key="item.filedCode"
                :is-multiple="false"
                :radio-list="item.options"
                :radio-value.sync="form[`${item.filedCode}`]"
                :title="item.title"
              />
            </template>
            <!-- 监测设备 -->
            <!--            <customPopCheckbox :is-multiple="false" :radio-list="outputldsArrList" :radio-value.sync="form.outputlds" title="监测设备" />-->
            <customPopCheckbox :list="selectOptionAll['环保-设备联动报警类别']" :check-value.sync="form.eventType" title="报警类别" />
            <customPopCheckbox :list="selectOptionAll['环保-报警预警级别']" :check-value.sync="form.alarmLevel" title="报警级别" />
            <customPopCheckbox :list="selectOptionAll['环保-报警状态']" :check-value.sync="form.reportStatus" title="报警状态" />
            <customPopCheckbox :list="selectOptionAll['是否']" :check-value.sync="form.falseAlarm" title="是否误报" />
            <customPopCheckbox :list="selectOptionAll['是否']" :check-value.sync="form.handleStatus" title="是否生成处置任务" />
          </template>
          <template v-else-if="active === '固危废报警'">
            <custom-timer title="固危废报警时间" type="datetime" :start.sync="form.starTime" :end.sync="form.endTime" />
            <customPopCheckbox :is-multiple="false" :radio-list="generateldsArrList" :radio-value.sync="form.generateIds" title="产生车间" />
            <customPopCheckbox :list="selectOptionAll['环保-固危废报警类别']" :check-value.sync="form.eventType" title="报警类别" />
            <customPopCheckbox :list="selectOptionAll['环保-报警预警级别']" :check-value.sync="form.alarmLevel" title="报警级别" />
            <customPopCheckbox :list="selectOptionAll['环保-报警状态']" :check-value.sync="form.reportStatus" title="报警状态" />
            <customPopCheckbox :list="selectOptionAll['是否']" :check-value.sync="form.falseAlarm" title="是否误报" />
            <customPopCheckbox :list="selectOptionAll['是否']" :check-value.sync="form.handleStatus" title="是否生成处置任务" />
            <!--  废物名称 -->
            <custom-pop-cascade
              ref="clearCascadeRef"
              :list="wasteCategoryDropList"
              :check-value.sync="form.wasteCategory"
              title="废物名称"
              cascader-title="废物名称"
              :must-last="true"
              @change="changeWasteHandler"
              @finish="finishHandler"
            />
          </template>
        </div>
        <div class="pop-bottom">
          <van-button type="default" @click="resetSuperSearch">清空</van-button>
          <van-button type="info" @click="handleSuperSearch">确认</van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
// import { companyList } from '@/api/enterprise'
import customTimer from '@/components/common/custom-timer1.vue'
import commonList from '@/assets/mixin/commonList'
import {
  outputAlarmList,
  plateDeviceAlarmList,
  plateVideoAlarmList,
  plateWasteAlarmList
} from '@/api/commonPage/AlarmManagement'
import {
  getDeviceDropList,
  getGenerateDropList,
  getHbRefCodeWasteDropList,
  getOutputDropList,
  getTargetDropList,
  getWasteCategoryDropList
} from '@/api/monitorAlarm'
import { prevTime } from '@/utils/dayJs'
import videoImg from '@/assets/images/common/video.jpg'

export default {
  components: {
    customTimer
  },
  mixins: [commonList],
  data() {
    return {
      videoImg,
      index: 0,
      active: '视频报警',
      form: {
        pageNum: 1,
        pageSize: 10,
        companylds: -1,
        starTime: '',
        endTime: '',
        // starTime: prevTime('年月日时分秒', 1, 'M'),
        // endTime: currentTime('年月日时分秒'),
        // eTime: currentTime('年月日时分秒'),
        // sTime: prevTime('年月日时分秒', 1, 'M'),
        eventType: '',
        alarmStatus: '',
        alarmLevel: '',
        falseAlarm: '',
        handleStatus: '',
        companyName: '',
        source: '-1',
        alarmSource: '',
        outputType: '',
        reportStatus: '',
        alarmltem: '',
        outputlds: '',
        productlds: '',
        devicelds: '',
        generateIds: '',
        wasteCategory: ''
      },
      equipmentRadio: [
        { options: [], filedCode: 'productlds', deviceType: 2, title: '生产设备' },
        { options: [], filedCode: 'devicelds', deviceType: 1, title: '治理设备' }
      ], // 设备
      list: [
        {
          label: '视频报警',
          listFun: plateVideoAlarmList
        },
        {
          label: '传感器报警',
          listFun: outputAlarmList
        },
        {
          label: '设备联动报警',
          listFun: plateDeviceAlarmList
        },
        {
          label: '固危废报警',
          listFun: plateWasteAlarmList
        }
      ],
      listFun: plateVideoAlarmList,
      current: '',
      listData: [],
      sourceAlarmList: [
        { label: '人工视频报警', text: '人工视频报警', value: 2 },
        { label: '企业提及报警', text: '企业提及报警', value: 3 }
      ],
      monitoringIndicatorsArr: [],
      outputldsArrList: [],
      generateldsArrList: [],
      wasteCategoryDropList: [],
      tagChangeFirstLoading: true,
      firstLoad: true,
      defaultTime: {
        sTime: '',
        eTime: ''
      }
    }
  },
  watch: {
    'form.alarmStatus'() {
      this.form.reportStatus = this.form.alarmStatus
    },
    'form.falseAlarm'() {
      this.form.isFalseReport = this.form.falseAlarm
    },
    'form.handleStatus'() {
      this.form.isHandleTask = this.form.handleStatus
    }
  },
  created() {
    this.$nextTick(() => {
      this.initGetTargetDropList()
      this.getOutputldsArrList()
      this.getEquipmentListHandler()
      this.generateldsArrListHandler()
      this.getWasteCategoryDropListFun()
    })
  },
  mounted() {
    const { current, active } = this.$route.query
    if (current) {
      this.current = current
    }
    if (active) {
      this.active = active
      this.list.map((v, ind) => {
        if (v.label === active) {
          this.index = ind
        }
      })
      this.listFun = this.list.find(v => v.label === this.active).listFun ? this.list.find(v => v.label === this.active).listFun : plateVideoAlarmList
    }
    this.companyList()
  },
  methods: {
    tagChange(tagArg) {
      this.index = tagArg.index
      this.active = tagArg.item.label
      this.listFun = tagArg.item.listFun
      this.form.pageNum = 1
      this.listData = []
      this.resetSuperSearch()
      // this.form.starTime = prevTime('年月日时分秒', 1, 'M')
      // this.form.endTime = currentTime('年月日时分秒')
      this.form.starTime = ''
      this.form.endTime = ''
      this.tagChangeFirstLoading = false
      this.firstLoad = true
      this.companyList()
    },
    /**
     * 获取废物名称 数据列表
     */
    async getWasteCategoryDropListFun() {
      try {
        const { data, status } = await getWasteCategoryDropList()
        if (status === 0) {
          this.wasteCategoryDropList = data.map(item => {
            return {
              text: item['codename'],
              value: item['codeid'],
              children: []
            }
          })
        }
      } catch (err) {
        console.log(err)
      }
    },
    /**
     * 废物名称 发生改变的回调
     * @param payload
     */
    async changeWasteHandler(payload) {
      try {
        const { data, status } = await getHbRefCodeWasteDropList({ categoryld: payload.value })
        if (status === 0) {
          const _infoItem = this.wasteCategoryDropList.find(b => b.value === payload.value)
          if (_infoItem.children && Array.isArray(_infoItem.children)) {
            _infoItem.children = data.map(l => {
              return {
                text: l['codename'],
                value: l['codeid']
              }
            })
          }
        }
      } catch (err) {
        console.log(err)
      }
    },
    /**
     * 获取产生车间数据列表
     */
    async generateldsArrListHandler() {
      try {
        const { data, status } = await getGenerateDropList()
        if (status === 0) {
          this.generateldsArrList = data.map(p => {
            return {
              label: p['codename'],
              text: p['codename'],
              value: p['codeid']
            }
          })
        }
      } catch (error) {
        console.log(error)
      }
    },
    /**
     * 完成选择后
     * @param payload
     */
    finishHandler(payload) {
      this.form.wasteCategory = payload[1].value
    },
    /**
     * 获取 生产设备 治理设备列表
     */
    async getEquipmentListHandler() {
      try {
        for (const item of this.equipmentRadio) {
          const { data, status } = await getDeviceDropList({ companylds: '', deviceType: item.deviceType })
          if (status === 0) {
            item.options = data.map(p => {
              return {
                label: p.deviceName || p['codename'] || p.outputName,
                text: p.deviceName || p['codename'] || p.outputName,
                value: p.deviceId || p['codeid'] || p['outputId']
              }
            })
          }
        }
      } catch (err) {
        console.log(err)
      }
    },
    /**
     * 获取 监测设备 列表
     */
    async getOutputldsArrList() {
      const { data, status } = await getOutputDropList({ companylds: '' })
      if (status === 0) {
        this.outputldsArrList = data.map(item => {
          return {
            label: item.outputName,
            text: item.outputName,
            value: item['outputId']
          }
        })
      }
    },
    /**
     * 获取传感器报警 - 检测指标列表
     */
    async initGetTargetDropList() {
      const { data, status } = await getTargetDropList()
      if (status === 0) {
        const targetDataList = []
        data.forEach(item => {
          targetDataList.push({
            label: item['codename'],
            text: item['codename'],
            value: item['codename']
          })
        })
        this.monitoringIndicatorsArr = targetDataList
      }
    },
    // 分页
    handlePages(value) {
      this.form.pageNum = value
      this.companyList()
    },
    // 企业名称查询
    handleSearch(value) {
      this.form.companyName = value
      this.form.pageNum = 1
      this.listData = []
      this.companyList()
    },
    // 高级查询
    handleSuperSearch() {
      this.superSearch = false
      this.form.pageNum = 1
      this.listData = []
      this.companyList()
    },
    // 级联选择器选择变化
    cascadeChange(args) {
      this.form.industryType = args.selectedOptions[args.selectedOptions.length - 1].text || ''
    },
    // 重置
    resetSuperSearch() {
      if (this.$refs.clearCascadeRef) this.$refs.clearCascadeRef.clearCascader()
      const pageSize = 10
      const pageNum = 1
      Object.keys(this.form).forEach(val => {
        this.form[val] = ''
      })
      this.$refs.customSearch.restore()
      this.form.pageSize = pageSize
      this.form.pageNum = pageNum
      this.form.companylds = -1
      this.form.starTime = this.defaultTime.sTime
      this.form.endTime = this.defaultTime.eTime
    },
    // 跳转详情
    goToDetails(item) {
      const { alarmId } = item
      this.$router.push({
        path: '/staging/AlarmManagementDetail',
        query: { monitorAlarmId: alarmId, current: this.current, active: this.active }
      })
    },
    // 返回工作台
    back() {
      this.$router.push({
        path: '/staging/monitor',
        query: { current: this.current }
      })
    },
    // 获取企业列表数据
    async companyList() {
      this.$refs.customLoadmore.loadStatus = true
      this.layout.showLoading()
      const { status, data } = await this.listFun(this.form)
      if (status === 0 && data) {
        this.total = data.total
        if (data.list[0]) {
          if (this.tagChangeFirstLoading || (this.form.starTime === '' && this.form.endTime === '')) {
            this.form.starTime = prevTime('年月日时分秒', 1, 'M', new Date(data.list[0].alarmTime || data.list[0].monitorTime))
            this.form.endTime = data.list[0].alarmTime || data.list[0].monitorTime
          }

          if (this.firstLoad) {
            this.defaultTime.sTime = prevTime('年月日时分秒', 1, 'M', new Date(data.list[0].alarmTime || data.list[0].monitorTime))
            this.defaultTime.eTime = data.list[0].alarmTime || data.list[0].monitorTime
            this.firstLoad = false
          }
        }
        data.list.map(val => {
          Object.keys(val).map(key => {
            val[key] = val[key] !== '' && val[key] !== undefined ? val[key] : '/'
          })
        })
        this.listData = this.listData.concat([...data.list])
        this.pages = data.pages
      }
      this.tagChangeFirstLoading = false
      this.$refs.customLoadmore.loadStatus = false
      this.layout.hideLoading()
    }
  }
}
</script>

<style lang="scss" scoped>
  .video_list_item {
    background: url('~@/assets/images/common/example.png') no-repeat;
    background-size: 100% 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 4.8rem;
    .content_title {
      padding: 10px;
      b, span {
        padding: 0 10px;
        background-color: rgba(0, 0, 0, 0.4);
        border: 0.0267rem solid #fff;
        font-weight: normal;
        font-size: 0.373rem;
        color: #fff;
      }
      b {
        background-color: rgba(252, 1, 1, 0.4);
      }
    }
    ul {
      background-color: rgb(15 57 105 / 29%);
      padding: 0.13333rem;
      color: #fff;
      li {
        margin-bottom: 0.133rem !important;
      }
    }
  }
</style>
